let ws = null;
let interval = null;
let timer = null;

export const connectSocket = () => {
    const pageStore = usePageStore();
    const userStore = useUserStore();
    disconnectSocket();

    if (process.env.NODE_ENV === "production") {
        if (!ws) {
            timer && clearTimeout(timer);
            let wsUrl = `wss://yzptonline.vrnewg.com?type=${pageStore.isMobile ? 2 : 1
                }&is_login=${userStore.isLogin && userStore.userInfo.id ? 1 : 2}`;
            if (userStore.isLogin && userStore.userInfo.id) {
                wsUrl += `&user_id=${userStore.userInfo.id || ""}`;
            }
            ws = new WebSocket(wsUrl);
            ws.onopen = () => {
                interval = setInterval(() => {
                    ws && ws.send("ping");
                }, 5 * 1000);
            };

            ws.onclose = () => {
                // 重连
                interval && clearInterval(interval);
                timer = setTimeout(() => {
                    connectSocket();
                }, 10000);
            };
        }
    }
};

export const disconnectSocket = () => {
    if (ws) {
        ws.close();
        interval && clearInterval(interval);
        ws = null;
        interval = null;
    }
};
